using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Tryit.Models;
using Tryit.Services;
using Tryit.Views;

namespace Tryit.ViewModels
{
    public class TemplateManagementViewModel : BindableBase
    {
        private readonly TemplateService _templateService;
        private CompositionTemplate _selectedTemplate;
        private Window _window;

        public ObservableCollection<CompositionTemplate> Templates { get; set; }

        public CompositionTemplate SelectedTemplate
        {
            get => _selectedTemplate;
            set => SetProperty(ref _selectedTemplate, value);
        }

        // 命令
        public DelegateCommand CreateTemplateCommand { get; }
        public DelegateCommand EditTemplateCommand { get; }
        public DelegateCommand CopyTemplateCommand { get; }
        public DelegateCommand DeleteTemplateCommand { get; }
        public DelegateCommand RefreshCommand { get; }
        public DelegateCommand ConfirmCommand { get; }
        public DelegateCommand CancelCommand { get; }

        public TemplateManagementViewModel()
        {
            _templateService = new TemplateService();
            Templates = new ObservableCollection<CompositionTemplate>();

            // 初始化命令
            CreateTemplateCommand = new DelegateCommand(ExecuteCreateTemplate);
            EditTemplateCommand = new DelegateCommand(ExecuteEditTemplate, CanExecuteEditTemplate)
                .ObservesProperty(() => SelectedTemplate);
            CopyTemplateCommand = new DelegateCommand(ExecuteCopyTemplate, CanExecuteCopyTemplate)
                .ObservesProperty(() => SelectedTemplate);
            DeleteTemplateCommand = new DelegateCommand(ExecuteDeleteTemplate, CanExecuteDeleteTemplate)
                .ObservesProperty(() => SelectedTemplate);
            RefreshCommand = new DelegateCommand(ExecuteRefresh);
            ConfirmCommand = new DelegateCommand(ExecuteConfirm);
            CancelCommand = new DelegateCommand(ExecuteCancel);

            LoadTemplates();
        }

        public void SetWindow(Window window)
        {
            _window = window;
        }

        private void LoadTemplates()
        {
            try
            {
                var templates = _templateService.GetAllTemplates();
                Templates.Clear();
                foreach (var template in templates)
                {
                    Templates.Add(template);
                }

                if (Templates.Any())
                {
                    SelectedTemplate = Templates.First();
                }
                else
                {
                    SelectedTemplate = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteCreateTemplate()
        {
            try
            {
                var dialog = new TemplateEditDialog();
                
                if (dialog.ShowDialog() == true)
                {
                    var newTemplate = dialog.Template;
                    if (newTemplate != null)
                    {
                        await _templateService.SaveTemplateAsync(newTemplate);
                        Application.Current.Dispatcher.Invoke(() => LoadTemplates());
                        MessageBox.Show("模板创建成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteEditTemplate()
        {
            if (SelectedTemplate == null) return;

            try
            {
                var dialog = new TemplateEditDialog(SelectedTemplate);
                
                if (dialog.ShowDialog() == true)
                {
                    var updatedTemplate = dialog.Template;
                    if (updatedTemplate != null)
                    {
                        await _templateService.SaveTemplateAsync(updatedTemplate);
                        Application.Current.Dispatcher.Invoke(() => LoadTemplates());
                        MessageBox.Show("模板更新成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"编辑模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteCopyTemplate()
        {
            if (SelectedTemplate == null) return;

            try
            {
                var newName = $"{SelectedTemplate.Name}_副本";
                var copyNumber = 1;
                while (_templateService.TemplateExists(newName))
                {
                    newName = $"{SelectedTemplate.Name}_副本_{copyNumber}";
                    copyNumber++;
                }

                var copiedTemplate = await _templateService.CopyTemplateAsync(SelectedTemplate.Name, newName);
                Application.Current.Dispatcher.Invoke(() => LoadTemplates());
                Application.Current.Dispatcher.Invoke(() => SelectedTemplate = Templates.FirstOrDefault(t => t.Name == newName));
                MessageBox.Show("模板复制成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"复制模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ExecuteDeleteTemplate()
        {
            if (SelectedTemplate == null) return;

            var result = MessageBox.Show($"确定要删除模板 '{SelectedTemplate.Name}' 吗？", 
                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
            
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    await _templateService.DeleteTemplateAsync(SelectedTemplate.Name);
                    Application.Current.Dispatcher.Invoke(() => LoadTemplates());
                    MessageBox.Show("模板删除成功！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除模板失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void ExecuteRefresh()
        {
            LoadTemplates();
        }

        private void ExecuteConfirm()
        {
            if (_window != null)
            {
                _window.DialogResult = true;
                _window.Close();
            }
        }

        private void ExecuteCancel()
        {
            if (_window != null)
            {
                _window.DialogResult = false;
                _window.Close();
            }
        }

        private bool CanExecuteEditTemplate()
        {
            return SelectedTemplate != null;
        }

        private bool CanExecuteCopyTemplate()
        {
            return SelectedTemplate != null;
        }

        private bool CanExecuteDeleteTemplate()
        {
            return SelectedTemplate != null && !SelectedTemplate.IsDefault;
        }
    }
} 